package zy.util;

import java.util.Random;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpProxy {
	private String api_domain;
    public HttpProxy(String domain){
        api_domain = domain;
    }
    /**
     * 计算字符串的MD5值
     * @param  signStr:签名字符串
     * @return
     */
    public String getSign(String signStr) {
    	try{
            String md5 = MD5.encryptMd5(signStr);
            return md5;
        } catch (Exception e) {
            e.printStackTrace();
            return  null ;
        }
    }

    /**
     * 仅供测试代码使用
     */
    public static String getClient_Sn(int codeLenth){
        while (true) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < codeLenth; i++) {
                if (i == 0)
                    sb.append(new Random().nextInt(9) + 1); // first field will not start with 0.
                else
                    sb.append(new Random().nextInt(10));
            }
            return sb.toString();
        }
    }

    /**
     * 终端激活
     * @param  code:激活码
     * @param  vendor_sn:服务商序列号
     * @param  vendor_key:服务商密钥
     * @param  code:激活码
     * @param  device_id:设备id
     * @return  {terminal_sn:"$终端号",terminal_key:"$终端密钥"}
     */
    public  JSONObject activate(String vendor_sn,String vendor_key,String code,String device_id){
        String url = api_domain + "/terminal/activate";
        JSONObject params = new JSONObject();
        try{
            params.put("code",code);//激活码
            params.put("device_id",device_id);//设备唯一身份ID
            params.put("type","2");//设备类型可以不提供。默认为"2"

            String sign = getSign(params.toString() + vendor_key);
            String result = HttpUtil.httpPost(url, params.toString(),sign,vendor_sn);
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200"))
                return null;
            String responseStr = retObj.get("biz_response").toString();
            JSONObject terminal = JSON.parseObject(responseStr);
            if(terminal.get("terminal_sn")==null || terminal.get("terminal_key")==null)
              return null;
            return  terminal;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 终端签到
     * @param  terminal_sn:终端号
     * @param  terminal_key:终端密钥
     * @param  device_id:设备id
     * @return  {terminal_sn:"$终端号",terminal_key:"$终端密钥"}
     */
    public  JSONObject checkin(String terminal_sn,String terminal_key,String device_id){
        String url = api_domain + "/terminal/checkin";
        JSONObject params = new JSONObject();
        try{
            params.put("terminal_sn",terminal_sn);                            //终端号
            params.put("device_id",device_id);   //设备唯一身份ID
            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(),sign,terminal_sn);
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200")){
            	return null;
            }
            String responseStr = retObj.get("biz_response").toString();
            JSONObject terminal = JSON.parseObject(responseStr);
            if(terminal.get("terminal_sn")==null || terminal.get("terminal_key")==null){
            	return null;
            }
            return  terminal;
        }catch (Exception e){
            return null;
        }
    }
    /**
     * 付款
     * @param  terminal_sn:终端号
     * @param  terminal_key:终端密钥
     * @param  client_sn:商户系统订单号,必须在商户系统内唯一；且长度不超过64字节
     * @param  total_amount:交易总金额,单位：元
     * @param  dynamic_id:条码内容
     * @param  subject:交易简介
     * @param  operator:门店操作员
     * @return
     */
    public JSONObject pay(String terminal_sn,String terminal_key,String client_sn,double total_amount,String dynamic_id,String subject,String operator){
        String url = api_domain + "/upay/v2/pay";
        JSONObject params = new JSONObject();
        try{
            params.put("terminal_sn",terminal_sn);         	//终端号
            params.put("client_sn",client_sn);  			//商户系统订单号,必须在商户系统内唯一；且长度不超过64字节
            params.put("total_amount",String.format("%.0f", 100*total_amount)); //交易总金额,以分为单位
            params.put("dynamic_id",dynamic_id);			//条码内容
            params.put("subject",subject);	                //交易简介
            params.put("operator",operator);	            //门店操作员

            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(),sign,terminal_sn);
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200")){
            	return null;
            }
            String responseStr = retObj.get("biz_response").toString();
            JSONObject resultJson = JSON.parseObject(responseStr);
            return  resultJson;
        }catch (Exception e){
            return null;
        }
    }
    
    /**
     * 查询
     * @param  terminal_sn:终端号
     * @param  terminal_key:终端密钥
     * @param  sn:收钱吧系统内部唯一订单号
     * @param  client_sn:商户系统订单号,必须在商户系统内唯一；且长度不超过64字节
     * @return {"result_code":"SUCCESS","error_code":"","error_message":"","data":{"sn":"7895253511213321","client_sn":"6353208695730307","client_tsn":"6353208695730307","trade_no":"399530133063201709202199993101","finish_time":"1505877787518","channel_finish_time":"1505877785000","status":"SUCCESS","order_status":"PAID","payway":"3","sub_payway":"1","payer_uid":"okSzXtyliELqYcs3KZe19o0SrB0w","payer_login":"","total_amount":"1","net_amount":"1","subject":"10斤猪肉","operator":"张三","payment_list":[{"type":"WALLET_WEIXIN","amount_total":"1"}]}}
     */
    public JSONObject query(String terminal_sn,String terminal_key,String sn,String client_sn){
        String url = api_domain + "/upay/v2/query";
        JSONObject params = new JSONObject();
        try{
            params.put("terminal_sn",terminal_sn);           //终端号
            params.put("sn",sn);             //收钱吧系统内部唯一订单号
            params.put("client_sn",client_sn);  //商户系统订单号,必须在商户系统内唯一；且长度不超过64字节
            String sign = getSign(params.toString() + terminal_key);
            String result = HttpUtil.httpPost(url, params.toString(),sign,terminal_sn);
            
            
            JSONObject retObj = JSON.parseObject(result);
            String resCode = retObj.get("result_code").toString();
            if(!resCode.equals("200")){
            	return null;
            }
            String responseStr = retObj.get("biz_response").toString();
            JSONObject resultJson = JSON.parseObject(responseStr);
            return  resultJson;
        }catch (Exception e){
            return null;
        }
    }
    
    public static void main(String[] args) {
        String code = "17410354";//激活码
        HttpProxy hp = new HttpProxy(CommonUtil.SQB_API_DOMAIN);
        String device_id = "omega_100_002_201709221025";
//        JSONObject result = hp.activate(CommonUtil.SQB_VENDOR_SN,CommonUtil.SQB_VENDOR_KEY,code,device_id); //激活
//        System.out.println(result);
        
        
        
        String terminal_sn = "100114020002045886";
		String terminal_key = "0c66bb66dc6d86c498bf5d963a709096";

//		JSONObject terminal = hp.checkin(terminal_sn, terminal_key,device_id);
//        System.out.println(terminal);
		
		
//		String client_sn = getClient_Sn(16);
//		Integer total_amount = 1;
//		String dynamic_id = "283332416894593744";
//		String subject = "10斤猪肉";
//		String operator = "张三";
//		JSONObject pay = hp.pay(terminal_sn, terminal_key, client_sn, total_amount, dynamic_id, subject, operator);
//		System.out.println(pay);
		
		String sn = "7895253594822866";
		String client_sn = "2298960752925275";
		JSONObject query = hp.query(terminal_sn, terminal_key, sn, client_sn);
		System.out.println(query);
	}
    
}
